package com.xz.xzutils.module.toolwindow.tabs;

import com.intellij.DynamicBundle;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.xz.xzutils.components.editor.FileTypeByExtension;
import com.xz.xzutils.components.editor.MyEditorHelper;
import com.xz.xzutils.settings.mybatislogplus.constant.FormatterEnum;
import com.xz.xzutils.utils.MySqlFormatter;

import java.awt.*;
import javax.swing.*;

/**
 * <p>
 *
 * </p>
 *
 * @author DONG.WANG17@HAND-CHINA.COM
 * @since 2025-01-04 23:16
 */
public class FormaterTab extends BaseTab implements Disposable {
    private final DynamicBundle messageBundle = new DynamicBundle(FormaterTab.class, "messages.MyPlugin");
    private Editor editor;
    private final JPanel editorContainer;
    private ComboBox<FileTypeByExtension> comboBox;
    private JButton formatButton;
    private String editorContent = "";
    private FileTypeByExtension fileType = FileTypeByExtension.json;

    public FormaterTab(Project project) {
        super("格式化");
        setTabName(messageBundle.getMessage("plugin.tab.formatter.title"));
        editorContainer = new JPanel(new BorderLayout());

        // 初始化组件
        initTypeSelector(project);
        initFormatButton(project);
        initEditor(project, FileTypeByExtension.json);

        // 构建界面
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(comboBox, BorderLayout.NORTH);
        mainPanel.add(editorContainer, BorderLayout.CENTER);
        mainPanel.add(formatButton, BorderLayout.SOUTH);
        setJComponent(mainPanel);
    }

    private void initEditor(Project project, FileTypeByExtension fileType) {
        // 释放旧编辑器资源
        if (editor != null) {
            editorContent = editor.getDocument().getText();
            EditorFactory.getInstance().releaseEditor(editor);
        }

        editor = MyEditorHelper.createEditor(project, fileType);
        // 正确清除并添加组件
        editorContainer.removeAll(); // 清除所有子组件
        editorContainer.add(editor.getComponent(), BorderLayout.CENTER);

        // 必须执行重绘
        editorContainer.revalidate();
        editorContainer.repaint();

        // 设置编辑器内容
        WriteCommandAction.runWriteCommandAction(project, () -> editor.getDocument().setText(editorContent));
        this.format(project);
    }

    private void initTypeSelector(Project project) {
        comboBox = new ComboBox<>(FileTypeByExtension.values());
        comboBox.setSelectedItem(fileType);
        comboBox.addActionListener(e -> {
            fileType = comboBox.getItem();
            initEditor(project, fileType);
            this.format(project);
        });
    }

    private void initFormatButton(Project project) {
        formatButton = new JButton(messageBundle.getMessage("plugin.tab.formatter.button.format"));
        formatButton.addActionListener(e -> {
            // 调用 idea 的格式化方法
            this.format(project);
        });
    }

    private void format(Project project) {
        // 调用 idea 的格式化方法
        WriteCommandAction.runWriteCommandAction(project, () -> {
            //if (fileType.equals(FileTypeByExtension.sql)) {
            //    try {
            //        String sqlFormat = MySqlFormatter.formatted(editor.getDocument().getText(), FormatterEnum.SqlFormatter);
            //        editor.getDocument().setText(sqlFormat);
            //    } catch (Exception ignored) {
            //
            //    }
            //} else {
            // 获取PSI文件并格式化
            PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (psiFile != null) {
                CodeStyleManager.getInstance(project).reformat(psiFile);
            }
            // }
        });
    }

    @Override
    public void dispose() {
        if (editor != null && !editor.isDisposed()) {
            EditorFactory.getInstance().releaseEditor(editor);
        }
    }
}
